<template>
  <el-card class="weather-widget">
    <div slot="header" class="clearfix">
      <span>当前天气</span>
    </div>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">加载失败，请稍后再试。</div>
    <div v-else class="weather-content">
      <h3>{{ weather.main.temp }}°C</h3>
      <p>{{ weather.weather[0].description }}</p>
    </div>
  </el-card>
</template>

<script>import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: 'WeatherWidget',
  setup() {
    const weather = ref({});
    const loading = ref(true);
    const error = ref(false);

    const fetchWeather = async () => {
      try {
        const response = await axios.get('https://api.openweathermap.org/data/2.5/weather', {
          params: {
            q: 'Beijing', // 你可以替换为你想要的城市
            units: 'metric', // 使用摄氏度
            appid: 'YOUR_API_KEY' // 替换为你的 OpenWeatherMap API Key
          }
        });
        weather.value = response.data;
      } catch (err) {
        error.value = true;
      } finally {
        loading.value = false;
      }
    };

    onMounted(() => {
      fetchWeather();
    });

    return {
      weather,
      loading,
      error
    };
  }
};
</script>

<style scoped>.weather-widget {
  width: 300px;
  text-align: center;
}

.loading, .error {
  color: red;
}

.weather-content h3 {
  margin: 0;
  font-size: 2em;
}

.weather-content p {
  margin: 0;
  font-size: 1.2em;
}
</style>